import React, { useImperativeHandle, forwardRef, useEffect, useState } from 'react'
import { Row, Col, Form, Select } from 'antd'
import { getContentRequest, getListRequest } from './ajax'
import { awaitWrap } from '@src/assets/js/tool'
import Dictionary from '@src/assets/js/dictionary'
const { Item } = Form
const { Option } = Select
const partTypes = ['申请人', '申请人代理人', '被申请人', '被申请人代理人', '鉴定机构', '其他']
const shortLabel = { span: 6 }

async function getOrgList (setList) {
  const [e, d] = await awaitWrap(getListRequest())
  if (e === null && d !== null) {
    setList(d)
  }
}

// 获取送达内容
async function getContent (topicType, actionSubject, c) {
  const [e, d] = await awaitWrap(getContentRequest({ topic_type: topicType, action_subject: actionSubject }))
  if (e === null && typeof d === 'string') {
    c.setFieldsValue({ content: d })
  }
}

// 改变主体
function changeSubject (pState, orgList, e, formRef, caseDetail, data, dispatch) {
  const d = caseDetail
  const c = formRef.current
  let list = []
  switch (e) {
    case '申请人':
      list = d.applicants.filter(li => li.status)
      break
    case '被申请人':
      list = d.respondents.filter(li => li.status)
      break
    case '申请人代理人':
      list = d.applicant_agents
      break
    case '被申请人代理人':
      list = d.respondents_agents
      break
    case '仲裁员':
      list = []
      break
    case '鉴定机构':
      list = orgList
      break
    case '其他':
      list = [{ name: '其他', id: '其他' }]
      break
    default:
      list = []
      break
  }
  dispatch({ type: 'contractList', data: list })
  // c.resetFields()
  getContent(pState.theme.type, e, c)
  c.setFieldsValue({
    action_subject: e,
    contractid: undefined,
    org_type: undefined
  })
}

// 改变当事人
function changeContractId (id, formRef, pState, onChangeContractId) {
  const c = formRef.current
  const { data, caseDetail, theme } = pState
  const caseid = caseDetail.id
  const type = c.getFieldValue('action_subject')
  let obj = null
  // c.resetFields()
  const list = pState.contractList
  for (let i = 0; i < list.length; i++) {
    if (list[i].id === id) {
      obj = list[i]
      break
    }
  }
  const o = {
    action_subject: type,
    contract_type: obj ? obj.subject_type : '',
    contract: obj && obj.name !== '其他' ? obj.name : '',
    contractid: id
  }
  if (type === '鉴定机构') {
    o.address = obj.address
  }
  c.setFieldsValue(o)
  onChangeContractId({
    caseid,
    id,
    data,
    theme,
    contractor: obj
  })
}

function Main ({
  formRef,
  pState,
  pDispatch,
  required = true,
  onChangeContractId = () => {}
}, ref) {
  const [types, setTypes] = useState([])
  const [orgList, setOrgList] = useState([])
  useImperativeHandle(ref, () => {
    return {
      changeSubject: (...args) => {
        changeSubject(pState, orgList, ...args)
      }
    }
  })
  useEffect(() => {
    const d = new Dictionary()
    d.init('鉴定机构类别')
      .then(() => {
        setTypes(d.getList('鉴定机构类别'))
      })
    getOrgList(setOrgList)
  }, [])
  useEffect(() => {
    if (formRef.current && orgList.length > 0) {
      const v = formRef.current.getFieldValue('action_subject')
      if (v === '鉴定机构') {
        pDispatch({ type: 'contractList', data: orgList })
      }
    }
  }, [formRef, orgList, pDispatch])
  return (
    <Row>
      <Col span={12}>
        <Item name='action_subject' label='仲裁地位' labelCol={shortLabel} wrapperCol={{ span: 17 }} rules={[{ required, message: '仲裁地位不能为空' }]}>
          <Select placeholder='请选中仲裁地位' onChange={e => changeSubject(pState, orgList, e, formRef, pState.caseDetail, pState.data, pDispatch)}>
            {partTypes.map(li => <Option key={li} value={li}>{li}</Option>)}
          </Select>
        </Item>
      </Col>
      <Item noStyle shouldUpdate={(prevValues, currentValues) => prevValues.action_subject !== currentValues.action_subject}>
        {({ getFieldValue }) =>
          getFieldValue('action_subject') === '鉴定机构' ? (
            <Col span={12}>
              <Form.Item label='' name='org_type' labelCol={0} wrapperCol={{ span: 22 }}>
                <Select placeholder='请选择机构类型' allowClear onChange={(e) => { pDispatch({ type: 'contractList', data: e ? orgList.filter(li => li.type === e) : orgList }) }}>
                  {
                    types.map((li, i) => {
                      return <Option value={li.value} key={i}>{li.value}</Option>
                    })
                  }
                </Select>
              </Form.Item>
            </Col>
          ) : null}
      </Item>
      <Item noStyle shouldUpdate={(prevValues, currentValues) => prevValues.action_subject !== currentValues.action_subject}>
        {({ getFieldValue }) => {
          const isOrg = getFieldValue('action_subject') === '鉴定机构'
          return (
            <Col span={isOrg ? 24 : 12}>
              <Item name='contractid' label={isOrg ? '机构名称' : ' '} labelCol={{ span: isOrg ? 3 : 0 }} colon={!isOrg} wrapperCol={{ span: isOrg ? 20 : 22 }} rules={[{ required, message: '名称不能为空' }]}>
                <Select placeholder='请选择名称/姓名' onChange={e => changeContractId(e, formRef, pState, onChangeContractId)}>
                  {
                    (pState.contractList || []).map(li => {
                      return <Option key={li.id} value={li.id}>{li.name}</Option>
                    })
                  }
                </Select>
              </Item>
            </Col>
          )
        }}
      </Item>
    </Row>
  )
}

export default forwardRef(Main)
